<template>
    <div class="order-form-container">
        <n-card :bordered="false">
            <h2>{{ isEdit ? "编辑订单" : "添加订单" }}</h2>

            <n-form :model="formData" :rules="formDataRule" ref="formRef" label-placement="left" label-width="120px" :style="{ maxWidth: '300px' }">
                <n-form-item label="订单名称" path="order_name">
                    <n-input v-model:value="formData.order_name" placeholder="请输入订单名称" />
                </n-form-item>
                <n-form-item label="用户ID" path="user_id">
                    <n-input v-model:value="formData.user_id" placeholder="请输入用户ID" />
                </n-form-item>
                <n-form-item label="订单类型" path="type">
                    <n-select v-model:value="formData.type" placeholder="请选择订单类型" :options="orderTypeTypes" />
                </n-form-item>
                <n-form-item label="订单状态" path="status">
                    <n-select v-model:value="formData.status" placeholder="请选择订单状态" :options="orderStatusTypes" />
                </n-form-item>
                <n-form-item label="AGV编号" path="car_index">
                    <n-input v-model:value="formData.car_index" placeholder="请输入AGV编号" />
                </n-form-item>
                <n-form-item label="订单优先级" path="priority">
                    <n-input v-model:value="formData.priority" placeholder="请输入订单优先级" />
                </n-form-item>
                <n-form-item label="订单起点" path="order_station_from">
                    <n-select v-model:value="formData.order_station_from" :options="stationOptions" placeholder="请选择订单起点" />
                </n-form-item>
                <n-form-item label="订单目的地" path="order_station_to">
                    <n-select v-model:value="formData.order_station_to" :options="stationOptions" placeholder="请选择订单目的地" />
                </n-form-item>

                <div class="form-actions">
                    <n-button @click="handleCancel">取消</n-button>
                    <n-button type="primary" :loading="loading" @click="handleSubmit">{{ isEdit ? '更新' : '提交'
                    }}</n-button>
                </div>
            </n-form>
        </n-card>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { NCard, NForm, NFormItem, NInput, NSelect, NButton, useMessage } from "naive-ui";
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import { API_URLS } from '../../utils/apiConfig';

const route = useRoute();
const router = useRouter();
const message = useMessage();

// 状态管理
const loading = ref(false);
const isEdit = ref(false);

const stationOptions = ref([]);

const get_station_options = async () => {
    try {
        const response = await axios.get(API_URLS.map_node.nameList);
        if (response.data.code === 200) {
            stationOptions.value = response.data.data.map(item => ({
                label: item[1],
                value: item[0]
            }));
            console.log(stationOptions.value);
        } else {
            message.error(`获取站点名称列表失败: ${response.data.msg}`);
        }
    } catch (error) {
        message.error("获取站点名称列表失败: " + error.message);
    }
}

// 订单类型和状态选项
const orderTypeTypes = [
    { label: "出库订单", value: "outbound" },
    { label: "入库订单", value: "inbound" },
    { label: "紧急订单", value: "emergency" },
    { label: "普通订单", value: "normal" },
]
const orderStatusTypes = [
    { label: "待处理", value: "pending" },
    { label: "处理中", value: "processing" },
    { label: "已完成", value: "completed" },
    { label: "已取消", value: "cancelled" },
]

const formData = ref({
    order_name: "",
    user_id: "",
    type: "",
    status: "",
    car_index: "",
    priority: "",
    order_station_from: "",
    order_station_to: "",
})

const formDataRule = {
    order_name: {
        required: true,
        message: "请输入订单名称",
        trigger: ["blur", "input"],
    },
    user_id: {
        required: true,
        message: "请输入用户ID",
        trigger: ["blur", "input"],
    },
    type: {
        required: true,
        message: "请输入订单类型",
        trigger: ["blur", "input"],
    },
    status: {
        required: true,
        message: "请选择订单状态",
        trigger: ["blur", "change"],
    },
    car_index: {
        required: true,
        message: "请输入AGV索引",
        trigger: ["blur", "input"],
    },
    priority: {
        required: true,
        message: "请输入订单优先级",
        trigger: ["blur", "input"],
    },
    order_station_from: {
        validator: (value) => value !== "",
        required: true,
        message: "请选择订单起点",
        trigger: ["blur", "change"],
    },
    order_station_to: {
        required: true,
        message: "请选择订单目的地",
        trigger: ["blur", "change"],
        validator: (value) => value !== "",
    },
}

// 提交表单
const handleSubmit = async () => {
    if (!formData.value) return;
    // await formData.value.validate();
    
    
    loading.value = true;
    try{
        // await formData.value.validate();
        const response = await axios.post(API_URLS.order.create, formData.value)

        if (response.data.code === 200) {
            message.success("订单创建成功");
            router.push("/order/order_list");
        } else {
            message.error("订单创建失败");
        }
    } catch (error) {
        message.error("网络异常");
    } finally {
        loading.value = false;
    }

}

// 取消操作
const handleCancel = () => {
  router.push("/order/order_list");
};

onMounted(async () => {
    await get_station_options();
    if (isEdit.value) {
        // 编辑订单时，从路由参数中获取订单ID
        const orderId = route.params.id;
        // 发送GET请求获取订单详情
        axios.get(`${API_URLS.ORDER_DETAIL}/${orderId}`)
            .then(response => {
                // 将返回的订单数据赋值给formData
                formData.value = response.data;
            })
            .catch(error => {
                message.error("获取订单详情失败");
            });
    }
});
</script>

<style scoped>
.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}
</style>
